package bookStore.tool;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import bookStore.po.User;
import bookStore.service.privilege.UserService;
import bookStore.service.privilege.UserServiceImpl;
import bookStore.vo.UserWithResources;

/**
 * 权限filter
 */
@WebFilter("/aaabbb")
public class ManagerFilter implements Filter {
	UserService userService = new UserServiceImpl();
    /**
     * Default constructor. 
     */
    public ManagerFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	@SuppressWarnings("unchecked")
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		HttpServletResponse httpResponse = (HttpServletResponse)response;
		HttpSession session = httpRequest.getSession();
		List<String> blackList = new ArrayList<>();
		//获取当前用户
		User currentUser = (User) session.getAttribute("currentUser");
		//未登录
		if(currentUser==null) {
			blackList = userService.getBlackList(-1);
			session.setAttribute("blackList", blackList);
		}else {
			blackList = (List<String>) session.getAttribute("blackList");
		}
		int index = httpRequest.getContextPath().length();
		String currentUrl=httpRequest.getRequestURI().substring(index);
		if(blackList.contains(currentUrl)) {
			httpResponse.sendRedirect("/bookStore1120/loginForm.jsp");
		}
		else {
			chain.doFilter(request, response);
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
